package com.huishi.handler.thread.task;

import com.huishi.entity.DataSource;
import com.huishi.entity.message.DBMsg;
import com.huishi.handler.thread.ThreadDataKeeper;
import com.huishi.util.DBUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步前准备任务：获取每张表的记录、记录总数
 */
public class BeforeSyncTask implements Runnable {

    private final ThreadDataKeeper threadDataKeeper;
    private final List<String> tables; // 要同步的表
    private final DataSource sourceDs; // 数据源

    public BeforeSyncTask(ThreadDataKeeper threadDataKeeper, List<String> tables, DataSource sourceDs) {
        this.threadDataKeeper = threadDataKeeper;
        this.tables = tables;
        this.sourceDs = sourceDs;
    }

    @Override
    public void run() {
        Map<String, DBMsg> dbMsgMap = new HashMap<>(tables.size());

        try (Connection sourceConn = DBUtils.genDBConn(sourceDs, sourceDs.getSchema())) {
            for (String table : this.tables) {
                String SQL = "SELECT * FROM " + table;

                Statement sourceStmt = sourceConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

                DBMsg dbMsg = new DBMsg();
                // 获取源所有记录
                ResultSet resultSet = sourceStmt.executeQuery(SQL);
                dbMsg.setResultSet(resultSet);
                dbMsg.setColumnCount(resultSet.getMetaData().getColumnCount());

                // 获取记录总数
                resultSet.last();
                threadDataKeeper.addTotalRow(resultSet.getRow());
                resultSet.beforeFirst();

                dbMsgMap.put(table, dbMsg);
            }

            threadDataKeeper.setDbSyncMsg(dbMsgMap);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
